import type { PromiseFn } from './useListRequest'

/**
 * select 远程搜索
 * @param request 请求方法
 * @param options 配置
 * @returns
 */
export function useSelectRemote<T extends PromiseFn>(
  request: T,
  options: {
    valueKey: string
    labelKey: string
    queryKey: string
    defaultState?: Record<string, any>
  }
) {
  const opts = ref<LabelValue[]>([])
  const loading = ref(false)
  const remoteMethod = async (query?: string) => {
    const { valueKey, labelKey, queryKey, defaultState = {} } = options
    loading.value = true
    try {
      const res = await request({
        limit: 0,
        offset: 0,
        ...defaultState,
        [queryKey]: query
      })

      opts.value = res!.list!.map((v: any) => ({
        label: v[labelKey]!,
        value: v[valueKey]!
      }))
    } finally {
      loading.value = false
    }
  }
  return { loading, remoteMethod, opts }
}
